package com.rds.document.controller;

import com.rds.common.annotation.Log;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.*;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.core.service.DocumentService;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.*;
import com.rds.common.utils.poi.ExcelUtil;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.common.utils.rds.HistoryRecordUtil;
import com.rds.common.utils.rds.ObjectReviseUtil;
import com.rds.common.workflowUtils.WorkflowUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 文档Controller
 * @author rds
 * @date 2021-04-19
 */
@RestController
@RequestMapping("/pms/doc")
public class RdaDocumentController extends BaseController
{
    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private DocumentService documentService;
    /** 文档表名 */
    private static final String tableName = "rda_document";
    /** 文件表名 */
    private static final String fileTableName = "rda_file";

    /**
     * 查询文档列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        //非超级管理员查询时加公司ID过滤数据
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            queryWrapper.add("and company_id="+SecurityUtils.getCompanyId());
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or title ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        List<HashMap<String,Object>> list=documentService.selectDocList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询我的文档列表
     */
    @GetMapping("/mydoc")
    public TableDataInfo mydoc(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or title ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        //加当前登录用户ID过滤数据
        queryWrapper.add("and ownerid="+SecurityUtils.getUserId());
        List<HashMap<String,Object>> list=documentService.selectDocList(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 获取文档详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        HashMap<String,Object> document=dynamicService.selectDataById(tableName,id);

        /*根据关系查询文档的文件夹路径及文件夹名称**/
        List<HashMap<String,Object>> folderRels=documentService.selectFolderRelListByDocId(id);
        StringBuilder path = new StringBuilder();
        StringBuilder folderPath = new StringBuilder();
        if(folderRels.size() > 0 ){
            for(HashMap<String,Object> folderRel:folderRels){
                String libraryName="";
                String folderName="";
                HashMap<String,Object> library = new HashMap<>();
                HashMap<String,Object> folder = new HashMap<>();
                if(StringUtils.isNotBlank(String.valueOf(folderRel.get("projectid")))){
                    library = dynamicService.selectDataById("rda_library",Long.valueOf(String.valueOf(folderRel.get("projectid"))));
                }
                if(StringUtils.isNotBlank(String.valueOf(folderRel.get("folderid"))) && !"0".equals(String.valueOf(folderRel.get("folderid")))){
                    folder = dynamicService.selectDataById("rda_folder",Long.valueOf(String.valueOf(folderRel.get("folderid"))));
                }
                if(library!=null){
                    libraryName = (String) library.get("name");
                }
                if(folder!=null){
                    folderName = (String) folder.get("name");
                }
                if(StringUtils.isNotBlank(libraryName) && StringUtils.isNotBlank(folderName)){
                    path.append(libraryName).append("--->").append(folderName).append("<br/>");
                }
                if(StringUtils.isNotBlank(folderName)){
                    folderPath.append(folderName).append("<br/>");
                }
            }
        }
        /*设置分类路径**/
        document.put("classfication",path.toString());
        /*设置文件夹名称**/
        document.put("folderName",folderPath.toString());

        /*查询公司名称**/
        if(document.get("company_id")!=null && !document.get("company_id").equals("")){
            HashMap<String,Object> company =  documentService.selectCompanyByCompanyId((Long) document.get("company_id"));
            if(company !=null){
                document.put("companyName",company.get("company_name"));
            }
        }
        //2022-01-24 查询该流程是否启动start
        DynamicVo dynamicVo = new DynamicVo();
        dynamicVo.setTableName("rda_workflow_object_rel");
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and objectid=" + id);
        dynamicVo.setQueryWrapper(queryWrapper);
        List<HashMap<String, Object>> rdaWorkflowObjectRelList =dynamicService.selectList(dynamicVo);
        for(HashMap<String,Object> workflowObjectRel:rdaWorkflowObjectRelList){
            HashMap<String, Object> getStateid=dynamicService.selectDataById("rda_workflow",Long.valueOf(workflowObjectRel.get("workflowid").toString()));
            if(getStateid!=null) {
                Long stateid =Long.valueOf(getStateid.get("stateid").toString());
                if (stateid.equals(WorkflowUtils.workflowCreateid)) {
                    document.put("isWorkflowStart","notStart");
                }else if(stateid.equals(WorkflowUtils.workflowActiveid) || stateid.equals(WorkflowUtils.workflowCompleteid)){
                    document.put("isWorkflowStart","hasStart");
                }
            }
        }
//        2022-01-24 查询该流程是否启动end
        return AjaxResult.success(document);
    }

    /**
     * 新增文档
     */
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Map<String, Object> data)
    {
        if(SecurityUtils.verifyPermissions("created", String.valueOf(data.get("stateid")))){
            return error("您没有此状态的创建权限！");
        }
        String documentName= String.valueOf(data.get("name"));
        List<?> fileList=new ArrayList<>();
        if (data.containsKey("fileList")) {
            fileList = (List<?>) data.get("fileList");
            data.remove("fileList");
        }
        /*查询是否存在同类型，同名称，同版本的文档*/
        List<HashMap<String,Object>> checkUniqueDocument=documentService.checkUniqueDocument((Integer) data.get("typeid"),String.valueOf(data.get("name")),String.valueOf(data.get("revision")));
        if(checkUniqueDocument.size() == 0){
            String username = SecurityUtils.getUsername();
            long userId = SecurityUtils.getUserId();
            long dId=SnowFlakeUtils.nextId();
            data.put("username",username);
            data.put("ownerid",userId);
            data.put("company_id",SecurityUtils.getCompanyId());
            data.put("id",dId);
            data.put("isfirstversion",true);/*创建时 首版本字段设置为true**/
            data.put("create_time",DateUtils.getNowDate());
            int rows = dynamicService.insertData(tableName,data);

            if(rows>0){
                /*如果有文件夹id创建文档与文件夹的关系*/
                Long folderId = (Long) data.get("parentid");
                if(folderId != null && folderId > 0){
                    int nun=documentService.insertRelDocAndFolder(dId,folderId, (Long) data.get("projectid"));
                }

                /*修改逻辑:创建页面附件不一定要上传 不上传时为空 2021-12-15****/
                StringBuilder fileNameSting;
                if(fileList.size()>0){
                    fileNameSting=documentService.insertBatchFile(fileList,dId);
                    /*创建文档时记录历史记录 2021-12-13*/
                    new HistoryRecordUtil(dynamicService).recordHistory(dId,"创建",(Integer) data.get("stateid"),"文档管理","创建文档；文档名称："+documentName+"，附件名称："+fileNameSting);
                }else{
                    /*创建文档时记录历史记录 2021-12-13*/
                    new HistoryRecordUtil(dynamicService).recordHistory(dId,"创建",(Integer) data.get("stateid"),"文档管理","创建文档；文档名称："+documentName);
                }
            }
            return WorkflowUtils.createWorkflowWithObject(Long.valueOf(String.valueOf(data.get("typeid"))),Long.valueOf(String.valueOf(data.get("policyid"))),Long.valueOf(String.valueOf(data.get("stateid"))),dId,"document",String.valueOf(data.get("name")));
//            return toAjax(rows);
        }else{
            return error("当前对象系统已存在! 名称:"+data.get("name")+",版本:"+data.get("revision"));
        }
    }

    /**
     * 添加已存在文档
     */
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping("/addExisting")
    @Transactional
    public AjaxResult addExisting(@RequestBody Map<String, Object> data)
    {
        String docIds= String.valueOf(data.get("ids"));
        String[] ids =docIds.split(",");
        Long parentId= (Long) data.get("parentid");
        Long projectId= (Long) data.get("projectid");
        int rows=documentService.addExisting(ids,parentId,projectId);
        return toAjax(rows);
    }

    /**
     * 修改文档
     */
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> data)
    {
        if(SecurityUtils.verifyPermissions("modify", String.valueOf(data.get("stateid")))){
            return error("您没有此状态的修改权限！");
        }
        /*直接更新当前文档对象**/
        Long dId= (Long) data.get("id");
        String username = SecurityUtils.getUsername();
        List<?> fileList=new ArrayList<>();
        if (data.containsKey("fileList")) {
            fileList = (List<?>) data.get("fileList");
            data.remove("fileList");
        }
        int rows = documentService.updateDocument(data);

        /*其次判断页面是否有附件传递过来**/
        StringBuilder fileNameSting= new StringBuilder();
        if(fileList.size()>0){
            fileNameSting=documentService.insertBatchFile(fileList,dId);
            /*创建文档时记录历史记录 2021-12-13*/
            new HistoryRecordUtil(dynamicService).recordHistory(dId,"修改",(Integer) data.get("stateid"),"文档管理","修改文档；新增附件名称："+fileNameSting);
        }else{
            /*创建文档时记录历史记录 2021-12-13*/
            new HistoryRecordUtil(dynamicService).recordHistory(dId,"修改",(Integer) data.get("stateid"),"文档管理","修改文档；");
        }
        return toAjax(rows);
    }

    /**
     * 删除文档
     */
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int successNum=0;
        int verifyNum=0;
        List<HashMap<String,Object>> docList= dynamicService.selectListByIds(tableName,ids);
        for (HashMap<String,Object> doc:docList){
            if(SecurityUtils.verifyPermissions("remove", String.valueOf(doc.get("stateid")))){
                verifyNum++;
            }else{
                Long docId=(Long) doc.get("id");
                int num=dynamicService.deleteDataById(tableName, docId);
                //删除文档附件
                ArrayList<String> wrapper=new ArrayList<>();
                wrapper.add("doc_id="+docId);
                dynamicService.deleteData(fileTableName, wrapper);
                //删除文档与文件夹关系
                ArrayList<String> folderWrapper=new ArrayList<>();
                folderWrapper.add("docid="+docId);
                dynamicService.deleteData("rda_folder_rel", folderWrapper);
                if(num>0){
                    successNum++;
                }
            }
        }
        return AjaxResult.getRemoveAjaxResult(successNum, verifyNum);
    }

    /** 文档导出 **/
    @Log(title = "文档管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Document document)
    {
        List<Document> list = new ArrayList<>();
        ExcelUtil<Document> util = new ExcelUtil<Document>(Document.class);
        return util.exportExcel(list, "文档数据");
    }

    /** 文档导入 **/
    @Log(title = "文档管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        System.out.println("[Class]RdaDocumentController:updateSupport = " + updateSupport);
        ExcelUtil<Document> util = new ExcelUtil<Document>(Document.class);
        List<Document> docList = util.importExcel(file.getInputStream());
        System.out.println("docList.size() = " + docList.size());
        String operName = SecurityUtils.getLoginUserName();
//        String message = documentService.importDocument(docList, updateSupport, operName);
//        return AjaxResult.success(message);
        return AjaxResult.success();
    }

    /**
     * 查询版本列表
     */
    @GetMapping("/version")
    public TableDataInfo version(Long id)
    {
        startPage();
        ObjectReviseUtil objectReviseUtil = new ObjectReviseUtil(dynamicService);
        List<Map<String, Object>> documents =objectReviseUtil.listDocumentVersion(dynamicService,id);
        return getDataTable(documents);
    }

    /**
     * 查询对象状态
     */
    @GetMapping("/lifecycle")
    public AjaxResult lifecycle(Long id)
    {
        Map<String, Object> document = dynamicService.selectDataById(tableName,id);
        List<HashMap<String,Object>> list=documentService.selectStateByPolicyId((Integer) document.get("policyid"));
        return AjaxResult.success(list);
    }

    /**
     * 文档管理-文档列表-详情页-版本管理-新增版本
     * @param id 当前需要修订的对象Id
     * @param floatFile 是否带文件修订
     * @return 修订成功或失败信息
     * copyEdition-->reviseObject
     */
    @GetMapping("/reviseObject")
    public AjaxResult reviseObject(Long id,boolean floatFile){
        /*判断权限*/
        Integer stateId = (Integer) dynamicService.selectDataById(tableName,id).get("stateid");
        if(SecurityUtils.verifyPermissions("revise", String.valueOf(stateId))) {
            return error("您没有此文档状态的修订权限！");
        }
        /*判断权限*/

        String message = "";
        int rows = -1;
        ObjectReviseUtil reviseUtil = new ObjectReviseUtil(dynamicService);
        AjaxResult result = reviseUtil.reviseObject(id,"document",floatFile);

        if ((int)result.get(AjaxResult.CODE_TAG) == 0){ //表示修订成功
            HashMap<String,Object> document=dynamicService.selectDataById(tableName,id);
            WorkflowUtils.createWorkflowWithObject(Long.valueOf(String.valueOf(document.get("typeid"))),Long.valueOf(String.valueOf(document.get("policyid"))),Long.valueOf(String.valueOf(document.get("stateid"))),id,"document",String.valueOf(document.get("name")));
            message = (String)result.get(AjaxResult.MSG_TAG);
            rows = 1;
        }else{
            message = (String)result.get(AjaxResult.MSG_TAG);
        }
        return rows > 0 ? success(message) : error(message);
    }

    /***
     * 查询当前文档下所有有效的文档附件
     * @param id 当前文档对象Id
     * @return 文档附件对象列表
     */
    @GetMapping("/queryFileList")
    public TableDataInfo queryFileList(Long id){
        startPage();
        List<HashMap<String,Object>> fileList=documentService.selectFileListByDocId(id);
        if(fileList.size() > 0 ){
            for (HashMap<String,Object> file : fileList) {
                file.put("fileSuffix",String.valueOf(file.get("name")).substring(String.valueOf(file.get("name")).lastIndexOf(".") + 1));
                String fileSize = String.valueOf(file.get("file_size"));
                long file_size = "null".equals(fileSize) || StringUtils.isBlank(fileSize) ? 0L : Integer.parseInt(fileSize);
                file.put("fileSize",documentService.readableFileSize(file_size));
            }
        }
        return getDataTable(fileList);
    }

    /**
     * 文档管理-文档列表-详情页-文档基本信息-新增文件
     * @param data 文档对象
     * @return 提示信息
     */
    @PostMapping("/addFile")
    public AjaxResult addFile(@RequestBody Map<String, Object> data){
        Long dId = (Long) data.get("projectid"); //这里还有些许不是很明白为什么这样写
        /*判断权限*/
        Integer stateId = (Integer) dynamicService.selectDataById(tableName,dId).get("stateid");
        if(SecurityUtils.verifyPermissions("created", String.valueOf(stateId))) {
            return error("您没有此文档状态的新增文件权限！");
        }
        /*判断权限*/
        List<?> fileList = (List<?>) data.get("fileList");
        if(fileList==null){
            return error("请选择需要上传的文件");
        }

        int count=0;
        int rows = 0;
        String username = SecurityUtils.getUsername();
        List<Map<String, Object>> fileBatchList=new ArrayList<>();
        StringBuilder fileNameSting= new StringBuilder();
        for (Object fileInfo : fileList) {
            if (fileInfo instanceof Map) { // 假设fileInfo是一个Map<String, Object>类型的对象
                Map<String, Object> fileMap=(Map<String, Object>) fileInfo;
                count++;

                DynamicVo fileDynamicVo=new DynamicVo();
                fileDynamicVo.setTableName(fileTableName);
                ArrayList<String> fileQueryWrapper=new ArrayList<>();
                fileQueryWrapper.add("and doc_id="+dId);
                fileQueryWrapper.add("and name='"+fileMap.get("fileName")+"'");
                fileDynamicVo.setQueryWrapper(fileQueryWrapper);
                List<HashMap<String,Object>> existFileList=dynamicService.selectList(fileDynamicVo);
                if(existFileList.size()>0){
                    count++;
                }else{
                    long fid=SnowFlakeUtils.nextId();
                    Map<String, Object> map=new HashMap<>();
                    map.put("id",fid);
                    map.put("doc_id",dId);
                    map.put("name",fileMap.get("fileName"));
                    map.put("path",fileMap.get("path").toString());
                    map.put("file_size",""+Integer.parseInt(fileMap.get("fileSize").toString())/1024);
                    map.put("username",username);
                    map.put("file_id",fid);
                    map.put("create_time",DateUtils.getNowDate());
                    fileNameSting.append(fileMap.get("fileName")).append(";");
                    fileBatchList.add(map);
                }
            }
        }
        rows=dynamicService.insertBatchData(fileTableName,fileBatchList);
        if(count>0){
            if(rows>0){
                /*创建文档时记录历史记录 2021-12-13*/
                new HistoryRecordUtil(dynamicService).recordHistory(dId,"新增文件",stateId,"文档管理","新增文件；名称："+fileNameSting);
                return AjaxResult.success("操作成功，"+count+"个文件已存在，请用更新文件操作！");
            }else{
                return AjaxResult.error("操作失败，已存在同文件名文件！");
            }
        }else{
            return toAjax(rows);
        }
    }

    /**
     * 文档管理-文档列表-详情页-文档基本信息-更新文件
     * @param data
     * @return 提示信息
     */
    @PutMapping("/UpdateFile")
    public AjaxResult UpdateFile(@RequestBody Map<String, Object> data){
        Long dId = Long.valueOf(String.valueOf(data.get("projectid")));
        /*判断权限*/
        Integer stateId = (Integer) dynamicService.selectDataById(tableName,dId).get("stateid");
        if(SecurityUtils.verifyPermissions("modify", String.valueOf(stateId))) {
            return error("您没有此文档状态的修改文件权限！");
        }
        /*判断权限*/
        List<?> fileList = (List<?>) data.get("fileList");
        if(fileList==null){
            return error("请选择需要上传的文件");
        }
        Map<String, Object> oldFile = dynamicService.selectDataById(fileTableName, (Long) data.get("id"));
        int row = 0;
        if(!(boolean) oldFile.get("locked") || oldFile.get("locker").equals(SecurityUtils.getUsername())){
            Map<String, Object> fileData=new HashMap<>();
            fileData.put("modify_time",DateUtils.getNowDate());
            fileData.put("status",2);
            ArrayList<String> updateWrapper=new ArrayList<>();
            updateWrapper.add("id="+oldFile.get("id"));
            dynamicService.updateData(fileTableName,fileData,updateWrapper);

            String username = SecurityUtils.getUsername();
            List<Map<String, Object>> fileBatchList=new ArrayList<>();
            StringBuilder fileNameSting= new StringBuilder();
            for(Object newFile : fileList){
                Map<String, Object> fileMap=(Map<String, Object>) newFile;
                long fid=SnowFlakeUtils.nextId();
                Map<String, Object> map=new HashMap<>();
                map.put("id",fid);
                map.put("doc_id",dId);
                map.put("name",fileMap.get("fileName"));
                map.put("path",fileMap.get("path").toString());
                map.put("file_size",""+Integer.parseInt(fileMap.get("fileSize").toString())/1024);
                map.put("username",username);
                map.put("file_id",oldFile.get("file_id"));
                map.put("create_time",DateUtils.getNowDate());
                map.put("modify_time",DateUtils.getNowDate());
                int revision=Integer.parseInt((String) oldFile.get("revision"))+1;
                map.put("revision",String.valueOf(revision));
                map.put("reason",data.get("changeReason"));
                fileNameSting.append(fileMap.get("fileName")).append(";");
                fileBatchList.add(map);
            }
            row=dynamicService.insertBatchData(fileTableName,fileBatchList);
            if(row>0){
                /*记录历史记录*/
                new HistoryRecordUtil(dynamicService).recordHistory(dId,"更新附件",stateId,"文档管理","附件名称："+fileNameSting);
            }else{
                return AjaxResult.error("操作失败!");
            }
        }else{
            return error("当前文件"+oldFile.get("name")+"已被用户:"+oldFile.get("locker")+"锁定,无法修改!");
        }
        return toAjax(row);
    }

    /**
     * 创建时-->点击取消时调用
     * 根据路径删除文件已提交至文件服务器的文件
     * 更换至S3时取消会出错修复
     * @param document 文档信息
     * @return 删除记录
     * */
     @PutMapping("/deleteFile")
     public AjaxResult deleteFile(@RequestBody Document document){
         // 上传文件路径
         boolean flag = false;
         List<File> fileList= document.getFileList();
         if(fileList !=null && fileList.size() > 0){
             for(File file : fileList){
                 file.setPath("");
                 file.setFileName("");
                 flag = true;
             }
         }else{
             //如果没有选择文件直接取消
             flag = true;
         }
         if(flag){
             return toAjax(1);
         }else{
            return error("文件删除失败文件路径错误");
         }
     }

    /**
     * 单个删除(删除此版本)
     * @param ids 文件id
     * @return 删除记录
     */
    @DeleteMapping("/removeFiles/{ids}")
    public AjaxResult removeFiles(@PathVariable Long[] ids){
        return removeFiles(ids,"");
    }

    /**
     * 批量删除(删除当前附件的所有版本)
     * @param ids 文件id
     * @return 删除记录
     */
    @DeleteMapping("/removeAllFiles/{delete}/{ids}")
    public AjaxResult removeAllFiles(@PathVariable Long[] ids,@PathVariable String delete){
        return removeFiles(ids,delete);
    }


    /***
     * 查询当前附件版本的全部版本
     * @param id 附件Id
     * @return 全部版本集合
     */
    @GetMapping("/selectAllRevision")
    public TableDataInfo selectAllRevision(Long id){
        startPage();
        /*这里传递过来的是附件的序号Id 并不是附件Id.所有先获取附件Id***/
        Map<String, Object> file = dynamicService.selectDataById(fileTableName, id);
        DynamicVo fileDynamicVo=new DynamicVo();
        fileDynamicVo.setTableName(fileTableName);
        ArrayList<String> fileQueryWrapper=new ArrayList<>();
        fileQueryWrapper.add("and file_id="+file.get("file_id"));
        fileDynamicVo.setQueryWrapper(fileQueryWrapper);
        List<HashMap<String,Object>> allFileRevision=dynamicService.selectList(fileDynamicVo);
        List<HashMap<String,Object>> allFile=new ArrayList<>();
        for (Object f : allFileRevision) {
            HashMap<String, Object> fileMap=(HashMap<String, Object>) f;
            fileMap.put("fileSuffix",String.valueOf(fileMap.get("name")).substring(String.valueOf(fileMap.get("name")).lastIndexOf(".")+1));
            allFile.add(fileMap);
        }
        return getDataTable(allFile);
    }


    /**
     * 删除所选的文件的方法(供删除操作调用)
     * @param ids 文档附件id
     * @param delete 删除此版本还是删除所有版本(all)
     * @return 是否锁定不让删除
     */
    private AjaxResult removeFiles(Long[] ids,String delete) {
        //查询当前勾选附件
        List<HashMap<String,Object>> fileList=dynamicService.selectListByIds(fileTableName,ids);
        //同一页面下所有附件关联的文档必定只有一个
        Long docId = (Long) fileList.get(0).get("doc_id");
        /*判断权限*/
        Integer stateId = (Integer) dynamicService.selectDataById(tableName,docId).get("stateid");
        if(SecurityUtils.verifyPermissions("remove", String.valueOf(stateId))) {
            return error("您没有此文档状态的删除文件权限！");
        }
        /*判断权限*/
        /*2021-12-24 更改附件删除逻辑
         * 1.如果是页面勾选多个(表格外按钮,传递all),表示要删除的是勾选附件的所有版本附件
         * 2.如果是行内删除,则只删除当前版本的附件,其余附件保留
         * ***/
        StringBuilder fileRemoveMessage = new StringBuilder(ids.length);
        int row = 0;
        for (Object file : fileList) {
            HashMap<String, Object> fileMap=(HashMap<String, Object>) file;
            if ((boolean) fileMap.get("locked")) {
                fileRemoveMessage.append(fileMap.get("name")).append("\\n");
            } else {
                if ("all".equalsIgnoreCase(delete)) { //表示删除当前版本所有版本附件
                    DynamicVo fileDynamicVo=new DynamicVo();
                    fileDynamicVo.setTableName(fileTableName);
                    ArrayList<String> fileQueryWrapper=new ArrayList<>();
                    fileQueryWrapper.add("and file_id="+fileMap.get("file_id"));
                    fileDynamicVo.setQueryWrapper(fileQueryWrapper);
                    List<HashMap<String,Object>> fileRevisionList=dynamicService.selectList(fileDynamicVo);
                    if(fileRevisionList.size() > 0){
                        row=dynamicService.deleteDataByIds(fileTableName, documentService.parseList2LongArray(fileRevisionList,"id"));
                    }else {
                        row=dynamicService.deleteDataById(fileTableName, (Long) fileMap.get("id"));
                    }
                    //历史记录
                    new HistoryRecordUtil(dynamicService).recordHistory((Long) fileMap.get("doc_id"),"删除文件所有版本",stateId,"文档管理",String.valueOf(fileMap.get("name")));
                    //break;
                } else { //表示删除当前版本,其余版本附件保留
                    row = dynamicService.deleteDataById(fileTableName, (Long) fileMap.get("id"));
                    /*如果有历史版本,将上一版本的状态设置为正常**/
                    DynamicVo fileDynamicVo=new DynamicVo();
                    fileDynamicVo.setTableName(fileTableName);
                    ArrayList<String> fileQueryWrapper=new ArrayList<>();
                    fileQueryWrapper.add("and file_id="+fileMap.get("file_id"));
                    fileDynamicVo.setQueryWrapper(fileQueryWrapper);
                    fileDynamicVo.setOrderBy(" revision desc");
                    List<HashMap<String,Object>> allFileRevision=dynamicService.selectList(fileDynamicVo);
                    if(row>0 && allFileRevision.size()>0){
                        Map<String, Object> fileData=new HashMap<>();
                        fileData.put("modify_time",DateUtils.getNowDate());
                        fileData.put("status",1);
                        ArrayList<String> updateWrapper=new ArrayList<>();
                        updateWrapper.add("id="+allFileRevision.get(0).get("id"));
                        dynamicService.updateData(fileTableName,fileData,updateWrapper);
                    }
                    //历史记录
                    new HistoryRecordUtil(dynamicService).recordHistory((Long) fileMap.get("doc_id"),"删除文件当前版本",stateId,"文档管理",fileMap.get("name")+"-->版本"+fileMap.get("revision"));
                }
            }
        }
        if (StringUtils.isNotBlank(fileRemoveMessage.toString())) {
            return error("以下文件处于锁定状态,无法删除\\n" + fileRemoveMessage);
        } else {
            return toAjax(row);
        }
    }

    @GetMapping("/locked/{id}")
    public AjaxResult fileLocked(@PathVariable Long id){
        HashMap<String,Object> file=dynamicService.selectDataById(fileTableName,id);
        Map<String, Object> fileData=new HashMap<>();
        fileData.put("modify_time",DateUtils.getNowDate());
        fileData.put("locked",true);
        ArrayList<String> updateWrapper=new ArrayList<>();
        updateWrapper.add("id="+file.get("id"));
        int row = dynamicService.updateData(fileTableName,fileData,updateWrapper);
        if(row>0){
            //历史记录
            HashMap<String,Object> document=dynamicService.selectDataById(tableName, (Long) file.get("doc_id"));
            new HistoryRecordUtil(dynamicService).recordHistory((Long) file.get("doc_id"),"锁定附件", (Integer) document.get("stateid"),"文档管理","锁定附件名称："+file.get("name"));
        }
        return toAjax(row);
    }

    @GetMapping("/unlock/{id}")
    public AjaxResult fileUnLock(@PathVariable Long id){
        HashMap<String,Object> file=dynamicService.selectDataById(fileTableName,id);
        String locker = (String) file.get("locker");
        if(locker.equals(SecurityUtils.getUsername()) && StringUtils.isNotBlank(locker)){
            Map<String, Object> fileData=new HashMap<>();
            fileData.put("modify_time",DateUtils.getNowDate());
            fileData.put("locked",false);
            ArrayList<String> updateWrapper=new ArrayList<>();
            updateWrapper.add("id="+file.get("id"));
            int row = dynamicService.updateData(fileTableName,fileData,updateWrapper);
            if(row>0){
                //历史记录
                HashMap<String,Object> document=dynamicService.selectDataById(tableName, (Long) file.get("doc_id"));
                new HistoryRecordUtil(dynamicService).recordHistory((Long) file.get("doc_id"),"锁定附件", (Integer) document.get("stateid"),"文档管理","锁定附件名称："+file.get("name"));
            }
            return toAjax(row);
        }else{
            return error("当前文件"+file.get("name")+"已被用户"+locker+"锁定,你无权限解除锁定!");
        }
    }

    /**
     * 查询所有无效的文档附件
     */
    @GetMapping("/queryInvalidFileList")
    public TableDataInfo queryInvalidFileList(Long id){
        DynamicVo dynamicVo=new DynamicVo();
        dynamicVo.setTableName(tableName);
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and doc_id="+id+" and status=2");
        dynamicVo.setQueryWrapper(queryWrapper);
        dynamicVo.setOrderBy(" revision desc");
        List<HashMap<String,Object>> allFileList=dynamicService.selectList(dynamicVo);
        List<HashMap<String,Object>> allFile=new ArrayList<>();
        for (Object f : allFileList) {
            HashMap<String, Object> fileMap=(HashMap<String, Object>) f;
            fileMap.put("fileSuffix",String.valueOf(fileMap.get("name")).substring(String.valueOf(fileMap.get("name")).lastIndexOf(".")+1));
            allFile.add(fileMap);
        }
        return getDataTable(allFile);
    }

    /**
     * 移除当前对象Id
     * @param ids 关系Ids
     * @return 提示信息
     */
    @Log(title = "移除", businessType = BusinessType.OTHER)
    @DeleteMapping("/disconnect/{ids}")
    public AjaxResult disconnect(@PathVariable Long[] ids)
    {
        return toAjax(dynamicService.deleteDataByIds("rda_folder_rel",ids));
    }
}
